package com.cmccgz.udacs_landlord_webapp.main.cardmanager;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.base.PermissionUtils;
import com.cmccgz.baselibrary.utils.InputMethodUtil;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.baselibrary.view.DatePickerDialog;
import com.cmccgz.baselibrary.view.DialogUtil;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.IdBean;
import com.cmccgz.udacs_landlord_webapp.data.Injection;
import com.cmccgz.udacs_landlord_webapp.main.housemanager.list.HouseListActivity;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;
import com.youtu.Youtu;

import java.io.File;
import java.util.Date;
import java.util.Locale;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.bilibili.boxing.AbsBoxingViewFragment.CAMERA_PERMISSIONS;


/**
 * 开卡授权页面
 */
public class CardAccreditActivity extends BaseActivity implements CardAccreditContract.View, View.OnClickListener {

    public static final String TAG = "CardAccreditActivity";
    public static final int CODE_REQUEST = 0x02;
    private CardAccreditContract.Presenter mPresenter;
    private ViewHelper mViewHelper;

    private EditText et_endtime;
    private EditText et_birth;
    private EditText et_username;
    private EditText et_userid;
    private EditText et_house;
    private EditText et_nation;
    private EditText et_usermobile;
    private RadioButton rb_female;
    private ImageView iv_scan;
    private final static int REQUEST_CAMERA=102;
    private String picPath;
    private PermissionUtils.PermissionAskCallback callBack=new PermissionUtils.PermissionAskCallback() {
        @Override
        public void hasPermissionDoNext() {
            if (ContextCompat.checkSelfPermission(mContext, CAMERA_PERMISSIONS[0]) != PERMISSION_GRANTED) {
                ToastUtils.show(mContext,"请开启摄像头权限！");
                return;
            }

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "cmccgz", System.currentTimeMillis()+".jpg");
            picPath=file.getAbsolutePath();
            Uri uri = Uri.fromFile(new File(picPath));
            //为拍摄的图片指定一个存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    };
    private Youtu youtu;
    private RadioGroup rg_sex;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_card_accredit;
    }

    @Override
    protected void beforePermission() {
        mViewHelper = ViewHelper.instance(mContext);
        if (mViewHelper != null) {
            mViewHelper.setTitle(R.string.title_activity_card_accredit);
            mViewHelper.setAllVisable(false);
            mViewHelper.setBackTextVisable(true);
        }
    }

    @Override
    protected void initView() {
        mPresenter = new CardAccreditPresenter(this, Injection.provideHouseManagerRepository());

        LinearLayout content = (LinearLayout) findViewById(R.id.contentFrame);
        et_username = (EditText) findViewById(R.id.et_username);
        rg_sex = ((RadioGroup) findViewById(R.id.rg_sex));
        rb_female = (RadioButton) findViewById(R.id.rb_female);
        et_userid = (EditText) findViewById(R.id.et_userid);
        et_nation = (EditText) findViewById(R.id.et_nation);
        et_usermobile = (EditText) findViewById(R.id.et_usermobile);
        et_house = (EditText) findViewById(R.id.et_house);
        et_endtime = (EditText) findViewById(R.id.et_endtime);
        et_birth = (EditText) findViewById(R.id.et_birth);
        iv_scan = ((ImageView) findViewById(R.id.iv_scan));
        Button btn_complete = (Button) findViewById(R.id.btn_complete);

        //设置不可编辑
        et_house.setKeyListener(null);
        et_nation.setKeyListener(null);
        et_birth.setKeyListener(null);
        et_endtime.setKeyListener(null);

        InputMethodUtil inputMethodUtil = new InputMethodUtil(this);
        inputMethodUtil.setupUI(content,et_username,et_usermobile,et_userid);

        //设置点击监听
        et_house.setOnClickListener(this);
        et_nation.setOnClickListener(this);
        et_birth.setOnClickListener(this);
        et_endtime.setOnClickListener(this);
        iv_scan.setOnClickListener(this);
        btn_complete.setOnClickListener(this);
        mViewHelper.setTitleOnClicklistener(this);

        mPresenter.start();
    }

    @Override
    protected void initFragment() {

    }


    @Override
    protected int setSystemBarColorId() {
        return 0;
    }

    @Override
    public void setPresenter(CardAccreditContract.Presenter presenter) {
        mPresenter = presenter;
    }


    @Override
    public void showEmptyName() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_name_tip);
    }

    @Override
    public void showInvalidName() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_invalid_name);
    }

    @Override
    public void showEmptyMobile() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_usermobile_tip);
    }

    @Override
    public void showInvalidMobile() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_invalid_usermobile);
    }

    @Override
    public void showEmptyIdNumber() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_userid_tip);
    }

    @Override
    public void showInvalidIdNumber() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_invalid_idnumber);
    }

    @Override
    public void showEmptyNation() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_nation_tip);
    }

    @Override
    public void showEmptyBirthDate() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_birthdate_tip);
    }

    @Override
    public void showEmptyHouse() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_house_tip);
    }

    @Override
    public void showEmptyEndTime() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_endtime_tip);
    }

    @Override
    public void showAllNation(String[] nations) {
        DialogUtil.showSelectDialog(mContext, getText(R.string.activity_cardaccredit_nation_dialong_title).toString(), nations, new DialogUtil.OnDialogItemClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, String vaule) {
                dialog.dismiss();
                et_nation.setText(vaule);
            }
        });
    }

    @Override
    public void showLoadingDialog() {
        showLoadingDialog(getText(R.string.activity_cardaccredit_loading).toString());
    }

    @Override
    public void hideLoadingDialog() {
        dismissLoadingDialog();
    }

    @Override
    public void showAccreditCardSuccess() {
        showToast(R.string.activity_cardaccredit_success);
        finish();
    }

    @Override
    public void showAccreditCardError(String errMsg) {
        showToast(errMsg);
    }

    @Override
    public void scanIdSuccess(IdBean idBean) {
        initIdResult(idBean);
        ToastUtils.show(mContext,"解析成功！");
        //删除图片
        boolean delete = new File(picPath).delete();
        Log.e(TAG, "scanIdSuccess: 删除文件："+picPath+(delete?"  成功":"失败") );
        dismissLoadingDialog();
    }

    private void initIdResult(IdBean idBean) {
        try {
            et_username.setText(idBean.getName());
            et_userid.setText(idBean.getId());
            et_nation.setText(idBean.getNation());
            if (!StringUtils.isEmpty(idBean.getSex())) {
                rg_sex.check("男".equals(idBean.getSex())? R.id.rb_male:R.id.rb_female);
            }
            String birth = idBean.getBirth();
            String[] split = birth.split("/");
            int year = Integer.parseInt(split[0]);
            int month = Integer.parseInt(split[1]);
            int day = Integer.parseInt(split[2]);
            et_birth.setText(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_format).toString(),year, month,day));
            et_birth.setTag(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_remote_format).toString(), year, month, day));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void scanIdError(String msg) {
        ToastUtils.show(mContext,msg);
        dismissLoadingDialog();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_endtime:
                hideSoftKeyboard(getCurrentFocus());
                DatePickerDialog.showDatePickerDialogWhitMinDate(mContext, getText(R.string.activity_cardaccredit_endtime_dialong_title).toString(), new Date().getTime(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        et_endtime.setText(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_format).toString(), year, monthOfYear + 1, dayOfMonth));
                        et_endtime.setTag(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_remote_format).toString(), year, monthOfYear + 1, dayOfMonth));
                    }
                });
                break;
            case R.id.et_birth:
                hideSoftKeyboard(getCurrentFocus());
                DatePickerDialog.showDatePickerDialogWhitMaxDate(mContext, getText(R.string.activity_cardaccredit_birth_dialong_title).toString(), new Date().getTime(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        et_birth.setText(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_format).toString(), year, monthOfYear + 1, dayOfMonth));
                        et_birth.setTag(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_remote_format).toString(), year, monthOfYear + 1, dayOfMonth));
                    }
                });
                break;
            case R.id.et_nation:
                hideSoftKeyboard(getCurrentFocus());
                mPresenter.selectNation();
                break;
            case R.id.et_house:
                hideSoftKeyboard(getCurrentFocus());
                Intent intent = new Intent(mContext, HouseListActivity.class);
                intent.putExtra(HouseListActivity.TYPE, HouseListActivity.TYPE_EXCHANGE);
                intent.putExtra(HouseListActivity.IS_FOR_SELECTED, true);
                startActivityForResult(intent, CODE_REQUEST);
                break;
            case R.id.btn_complete:
                String name = et_username.getText().toString();
                String sex = rb_female.isChecked() ? getText(R.string.sex_women).toString() : getText(R.string.sex_man).toString();
                String idNumber = et_userid.getText().toString();
                String nation = et_nation.getText().toString();
                String birth = et_birth.getTag() == null ? "" : et_birth.getTag().toString();
                String endTime = et_endtime.getTag() == null ? "" : et_endtime.getTag().toString();
                String usermobile = et_usermobile.getText().toString();
                String mobile = AppConfig.getMobile(mContext);
                String houseId = et_house.getTag() == null ? "" : et_house.getTag().toString();
                mPresenter.completeCardAccredit(mobile, usermobile, name, sex, idNumber, nation, birth, houseId, endTime);
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.iv_scan:
                PermissionUtils.askPermission(this,101,callBack, Manifest.permission.CAMERA);
                break;
            default:

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST && resultCode == HouseListActivity.RESULT_CODE) {
            String house_name = data.getStringExtra(HouseListActivity.HOUSE_NAME);
            String house_id = data.getStringExtra(HouseListActivity.HOUSE_ID);
            et_house.setText(house_name);
            et_house.setTag(house_id);
        }
        if (resultCode==RESULT_OK
                &&requestCode==REQUEST_CAMERA
                && !StringUtils.isEmpty(picPath)
                &&new File(picPath).exists()) {
            showLoadingDialog("正在解析身份证信息...");
            //解析
            mPresenter.scanId(picPath);
        }
    }

    public void instanceYoutu() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 101){
            PermissionUtils.handlePermissionRequest(permissions, grantResults, this, callBack, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }

            });
        }
    }
}
